package com.atguigu.gmall.item.rpc;

import com.atguigu.gmall.common.constant.RedisConst;
import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.feign.search.SearchFeignClient;
import com.atguigu.gmall.item.service.SkuDetailService;
import com.atguigu.gmall.product.vo.ItemDataVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @author lfy
 * @Description
 * @create 2023-07-15 14:02
 */
@Slf4j
@RequestMapping("/api/inner/item")
@RestController
public class SkuDetailRpcController {


    @Autowired
    SkuDetailService skuDetailService;

    @Autowired
    StringRedisTemplate redisTemplate;

    @Autowired
    SearchFeignClient searchFeignClient;

    @Autowired
    ThreadPoolExecutor executor;

    /**
     * 获取商品详情
     * @param skuId
     * @return
     */

    @GetMapping("/detail/{skuId}")
    public Result<ItemDataVo> skuDetail(@PathVariable Long skuId){
        log.info("商品详情{}-正在查询...",skuId);

        //1、获取商品详情
        ItemDataVo dataVo =  skuDetailService.getSkuDetail(skuId);

        //2、更新热度分； 每攒够100分，更新一次。 redis里面保存实时分数，对100求余==0，再去es统一更新成最新的分
        CompletableFuture.runAsync(()->{
            Long increment = redisTemplate.opsForValue().increment(RedisConst.HOTSCORE_SKU + skuId);
            if (increment % 100 == 0) {
                log.info("商品：【{}】热度分更新：【{}】",skuId,increment);
                searchFeignClient.incrHotScore(skuId,increment);
            }
        },executor);


        return Result.ok(dataVo);
    }
}
